// pages/album/index.js
import request from '../../utils/request'
import Datetime from '../../utils/datetime'
import calc from '../../utils/calc'
import WxNotificationCenter from '../../utils/WxNotificationCenter'

const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: 0,
    album: {},
    postsData: { },
    share: false,
    isInited: false,
    isComment: false,
    commentIndex: -1,
    commentText: '',
    commentTo: null,
    rewardData: {
      rewardAmount: 0,
      rewardIndex: -1,
      showCenterDialog: false,
      isEditing: false
    }
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let is_invite = options.is_invite
    this.setData({
      id: options.id,
      share: options.share
    })
    // 获取相册基本信息
    this.fetchAlbum()
    // 获取post列表数据
    this.initData()
    // 如果是邀请链接，将新用户加入
    if (is_invite) {
      if (app.globalData.account) {
        // 加入相册
        this._joinAlbum()
      } else {
        app.accountReadyCallback = res => {
          this._joinAlbum()
        }
      }
    }
    let that = this
    WxNotificationCenter.addNotification("refreshPosts", that.refreshPosts, that)
    WxNotificationCenter.addNotification("removeFollower", that.removeFollower, that)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.showLoading({
      title: '刷新中...',
    })
    this.initData(function () {
      wx.hideLoading()
      wx.stopPullDownRefresh()
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.loadMore()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    if (res.from === 'button') {
      let shareIndex = res.target.dataset.index
      let post = this.data.postsData.results[shareIndex]
      let elem = post.attachments[0]
      let imageUrl = ''
      if (elem.file_type == 0) {
        imageUrl = elem.file
      } else {
        imageUrl = elem.file + '?vframe/png/offset/1'
      }
      return {
        title: post.text,
        path: '/pages/album/post?id=' + post.id,
        imageUrl: imageUrl
      }
    } else {
      let post = this.data.postsData.results[0]
      return {
        title: post.text,
        path: '/pages/album/post?id=' + post.id
      }
    }
  },

  /*
   * 刷新posts信息
   */
  refreshPosts: function (obj) {
    let album = this.data.album
    if (obj) {
      album.attachments_count += obj.cnum
      this.setData({ album: album })
    }
    this.initData(null)
  },

  /*
   * 移除成员
   */
  removeFollower: function (obj) {
    let album = this.data.album
    if (obj) {
      album.follower_count -= obj.rnum
      this.setData({ album: album })
    }
  },

  /*
   * 获取相册信息
   * 直接从globalData里面获取
   */
  fetchAlbum() {
    let share = this.data.share
    let albums = app.globalData.albums
    if (!share) {
      let id = this.data.id
      let album = {}
      for (let i = 0; i < albums.length; i++) {
        let item = albums[i]
        if (item.id == id) {
          album = item
          break;
        }
      }
      this.setData({ album: album })
    } else {
      // 如果是分享进来的，需要拉取相册信息(要求有创建的账号)
      if (app.globalData.account) {
        // 加入相册
        this._requestAlbum()
      } else {
        app.accountReadyCallback = res => {
          this._requestAlbum()
        }
      }
    }
  },

  /*
   * 请求获取Album
   */
  _requestAlbum() {
    let that = this
    let url = app.globalData.apiHost + '/albums/' + this.data.id
    wx.showLoading({
      mask: true,
      title: '正在加载...',
    })
    request(url, 'GET', app.globalData.loginToken, {}, function (err, data) {
      wx.hideLoading()
      if (!err) {
        that.setData({
          album: data
        })
      }
    })
  },


  /*
   * 初始化post数据
   */
  initData(callback) {
    let that = this
    let url = app.globalData.apiHost + '/albums/' + this.data.id + '/posts/'
    request(url, 'GET', app.globalData.loginToken, {}, function (err, data) {
      console.log(data)
      if (!err) {
        that._setDatetime(data)
        that.setData({ postsData: data, isInited: true })
      }
      if (callback) {
        return callback()
      }
    })
  },
  

  /*
   * 加载更多数据
   */
  loadMore() {
    let that = this
    let postsData = this.data.postsData
    if (postsData.next) {
      request(postsData.next, 'GET', app.globalData.loginToken, {}, function (err, data) {
        if (!err) {
          that._setDatetime(data)
          postsData.next = data.next
          postsData.previous = data.previous
          postsData.results = postsData.results.concat(data.results)
          that.setData({ postsData: postsData })
        }
      })
    }
  },

  /*
   * 操作时间
   */
  _setDatetime(data) {
    for (let i = 0; i < data.results.length; i++) {
      let item = data.results[i]
      let datetime = new Datetime(item.created)
      item.createTime = datetime.getDateStr()
    }
  },

  /*
   * 加入相册
   */
  _joinAlbum: function () {
    let that = this
    let url = app.globalData.apiHost + '/albums/' + this.data.id + '/join/'
    request(url, 'POST', app.globalData.loginToken, {}, function (err, data) {
      console.log(data)
      if (!err) {
        wx.showToast({
          title: '加入相册成功',
        })
      }
    })
  },

  /*
   * 分享post
   */
  sharePost: function(e) {
  },

  /*
   * 查看相册设置
   */
  viewSetting: function (e) {
    wx.navigateTo({
      url: 'setting?id=' + this.data.id,
    })
  },

  /*
   * 查看post详情
   */
  viewPost: function (e) {
    let id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: 'post?id=' + id + '&albumId=' + this.data.id,
    })
  },

  /*
   * 查看小金库
   */
  viewBank: function (e) {
    wx.navigateTo({
      url: 'bank?id=' + this.data.id,
    })
  },

  /*
   * 打赏照片的对话框
   */
  rewardDialog: function (e) {
    let index = e.currentTarget.dataset.index
    let rewardAmount = calc.getRandomNum(0.1, 20)
    this.setData({
      rewardData: {
        showCenterDialog: true,
        rewardAmount: rewardAmount,
        isEditing: false,
        rewardIndex: index
      }
    })
  },

  /*
   * 取消打赏
   */
  closeReward: function (e) {
    this.setData({
      rewardData: {
        showCenterDialog: false,
        rewardAmount: 0,
        isEditing: false,
        rewardIndex: -1
      }
    })
  },

  /*
   * 刷新打赏金额
   */
  refreshReward: function (e) {
    let rewardData = this.data.rewardData
    let rewardAmount = calc.getRandomNum(0.1, 20)
    rewardData.rewardAmount = rewardAmount
    this.setData({
      rewardData: rewardData
    })
  },

  /*
   * 确认打赏
   */
  confirmReward: function (e) {
    let rewardData = this.data.rewardData
    let rewardAmount = rewardData.rewardAmount
    let postsData = this.data.postsData
    if (isNaN(rewardAmount)) {
      return wx.showToast({
        title: '请输入数字',
        image: '/images/icon/icon_attention.png'
      })
    }
    if (rewardAmount > 200) {
      return wx.showToast({
        title: '打赏金额不能超过200',
        image: '/images/icon/icon_attention.png'
      })
    }
    wx.showLoading({
      title: '请求中...',
      mask: true
    })
    let post = postsData.results[rewardData.rewardIndex]
    let that = this
    let signData = {
      album: this.data.album.id,
      post: post.id,
      fee: rewardAmount * 100
    }
    let signUrl = app.globalData.apiHost + '/pay/get_wechat_prepay_id/'
    // 需要请求后台获取签名
    request(signUrl, 'post', app.globalData.loginToken, signData, function (err, data) {
      wx.hideLoading()
      if (!err) {
        let timeStamp = data.timeStamp.toString()
        wx.requestPayment({
          'timeStamp': timeStamp,
          'nonceStr': data.nonceStr,
          'package': data.package,
          'signType': data.signType,
          'paySign': data.paySign,
          success: function (res) {
            console.log(res)
            // 支付成功
            post.is_bought = true
            rewardData = {
              showCenterDialog: false,
              rewardAmount: 0,
              isEditing: false,
              rewardIndex: -1
            }
            that.setData({ postsData: postsData, rewardData: rewardData })
            wx.showToast({
              title: '打赏成功',
            })
          },
          fail: function (res) {
            console.log(res)
          }
        })
      }
    })
  },

  /*
   * 编辑打赏金额
   */
  editAmount: function (e) {
    let rewardData = this.data.rewardData
    rewardData.isEditing = true
    this.setData({ rewardData: rewardData })
  },

  rewardAmountChange: function (e) {
    let rewardData = this.data.rewardData
    rewardData.rewardAmount = e.detail.value
    this.setData({ rewardData: rewardData })
  },

  endEditAmount: function (e) {
    let rewardData = this.data.rewardData
    rewardData.isEditing = false
    this.setData({ rewardData: rewardData })
  },

  /*
   * 删除post
   */
  removePost: function (e) {
    let index = e.currentTarget.dataset.index
    let postsData = this.data.postsData
    let post = postsData.results[index]
    let album = this.data.album
    let that = this
    if (post.author.id == app.globalData.account.id) {
      // 若是自己发的，可以删除
      wx.showActionSheet({
        itemList: ['删除'],
        success: function (res) {
          if (!res.tapIndex) {
            let data = { post: post.id }
            let url = app.globalData.apiHost + '/albums/post/' + post.id
            request(url, 'DELETE', app.globalData.loginToken, data, function (err, data) {
              if (!err) {
                // 删除成功
                postsData.count--
                postsData.results.splice(index, 1)
                album.attachments_count -= post.attachments.length
                that.setData({ postsData: postsData, album: album })
                WxNotificationCenter.postNotificationName('refreshPosts')
              }
            })
          } 
        }
      })
    } else {
      wx.showActionSheet({
        itemList: ['举报'],
        success: function (res) {
          if (!res.tapIndex) {
            wx.showModal({
              title: '提示',
              content: '是否确定举报该内容？',
              success: function (res) {
                let url = app.globalData.apiHost + '/albums/post/' + post.id + '/report/'
                request(url, 'POST', app.globalData.loginToken, {}, function (err, data) {
                  console.log(err)
                  if (!err) {
                    wx.showToast({
                      title: '举报成功',
                    })
                  }
                })
              }
            })
          }
        }
      })
    }
    
  },

  /*
   * 查看图片大图
   */
  viewImages: function (e) {
    let postIndex = parseInt(e.currentTarget.dataset.postindex)
    let imgIndex = parseInt(e.currentTarget.dataset.index)
    let post = this.data.postsData.results[postIndex]
    let images = []
    let currentImg = ''
    for (let i=0; i < post.attachments.length; i++) {
      let item = post.attachments[i]
      if (item.file_type == 0) {
        images.push(item.file)
      }
      if (imgIndex == i) {
        currentImg = item.file
      }
    }

    wx.previewImage({
      urls: images,
      current: currentImg
    })
  },

  /*
   * 播放视频
   */
  playVideo: function (e) {
    let postIndex = parseInt(e.currentTarget.dataset.postindex)
    let videoIndex = parseInt(e.currentTarget.dataset.index)
    let post = this.data.postsData.results[postIndex]
    let videoId = 'video_' + postIndex + '_' + videoIndex
    this.videoCtx = wx.createVideoContext(videoId)
    this.videoCtx.play()
    this.videoCtx.requestFullScreen()
  },

  /*
   * 视频播放暂停
   */
  videoPause: function () {
    console.log('videoPause')
  },

  /*
   * 视频全屏事件
   */
  videoFullScreenChange: function (e) {
    if (!e.detail.fullScreen) {
      this.videoCtx.pause()
    }
  },

  /*
   * 去上传图片
   */
  uploadMedia: function () {
    let that = this
    let medias = []
    wx.showActionSheet({
      itemList: [
        '添加图片',
        '添加视频'
      ],
      success: function (res) {
        if (res.tapIndex == 0) {
          // 添加图片
          wx.chooseImage({
            count: 9,
            sourceType: ['album'],
            success: function (res) {
              for (let i = 0; i < res.tempFilePaths.length; i++) {
                let item = { path: res.tempFilePaths[i], type: 0 }
                medias.push(item)
              }
              let mediaStr = JSON.stringify(medias)
              wx.navigateTo({
                url: 'upload?id=' + that.data.id + '&medias=' + mediaStr,
              })
            },
          })
        } else {
          // 添加视频
          wx.chooseVideo({
            sourceType: ['album'],
            success: function (res) {
              let item = { path: res.tempFilePath, type: 1, duration: res.duration }
              medias.push(item)
              let mediaStr = JSON.stringify(medias)
              wx.navigateTo({
                url: 'upload?id=' + that.data.id + '&medias=' + mediaStr,
              })
            }
          })
        }
      }
    })
    
  },

  /*
   * 写评论
   * 设置一个固定的input，一旦开始编辑，就让他的focus为true
   */
  writeComment: function (e) {
    let index = parseInt(e.currentTarget.dataset.index)
    // 设置评论输入状态
    this.setData({
      isComment: true,
      commentIndex: index
    })
  },

  /*
   * 回复评论
   */
  replyComment: function (e) {
    let index = parseInt(e.currentTarget.dataset.index)
    let toIndex = parseInt(e.currentTarget.dataset.toindex)
    let postsData = this.data.postsData
    let post = postsData.results[index]
    let commentTo = post.comments[toIndex]
    let that = this
    if (app.globalData.account.id == commentTo.author.id) {
      // 提示用户删除评论
      wx.showActionSheet({
        itemList: ['删除评论'],
        success: function (res) {
          if (!res.tapIndex) {
            let data = { id: commentTo.id }
            let url = app.globalData.apiHost + '/albums/comments/' + commentTo.id + '/delete/'
            request(url, 'DELETE', app.globalData.loginToken, data, function (err, data) {
              if (!err) {
                // 删除成功
                post.comments_count --
                post.comments.splice(toIndex, 1)
                that.setData({ postsData: postsData })
              }
            })
          }
        }
      })
    } else {
      this.setData({
        isComment: true,
        commentIndex: index,
        commentTo: commentTo,
      })
    }
    
  },

  /*
   * 放弃评论
   */
  giveupComment: function (e) {
    this.setData({
      isComment: false,
      commentIndex: -1,
      commentText: '',
      commentTo: null
    })
  },

  /*
   * 评论编辑了
   */
  commentTextChange: function (e) {
    this.setData({
      commentText: e.detail.value
    })
  },

  /*
   * 发评论
   */
  sendComment: function (e) {
    let text = this.data.commentText
    let index = this.data.commentIndex
    let postsData = this.data.postsData
    let post = postsData.results[index]
    this.setData({
      isComment: false,
      commentIndex: -1,
      commentText: '',
    })
    let that = this
    let data = {
      post: post.id,
      author: app.globalData.account.id,
      text: text
    }
    if (this.data.commentTo) {
      data.to = this.data.commentTo.id
    }
    let url = app.globalData.apiHost + '/albums/post/' + post.id + '/comments/'
    request(url, 'POST', app.globalData.loginToken, data, function (err, data) {
      if (!err) {
        console.log(data)
        // 创建成功，添加到评论列表
        post.comments.unshift(data)
        post.comments_count ++
        that.setData({ postsData: postsData, commentTo: null })
      }
    })
  },

  /*
   * 取消评论
   */
  cancelComment: function (e) {
    this.setData({
      isComment: false,
      commentIndex: -1,
      commentText: '',
      commentTo: null
    })
  },

  /*
   * 提交formId
   */
  formSubmit: function (e) {
    if (e.detail) {
      app.uploadFormId(e.detail.formId, function (err) { })
    }
  },

})